package com.itheima.mm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mm.mapper.CompanyMapper;
import com.itheima.mm.mapper.IndustryMapper;
import com.itheima.mm.pojo.Company;
import com.itheima.mm.pojo.Industry;
import com.itheima.mm.service.CompanyService;
import com.itheima.mm.vo.CompanyVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description CompanyServiceImpl
 * @Author xiao
 * @Date 2024-06-26
 */

@Service
public class CompanyServiceImpl implements CompanyService{

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private IndustryMapper industryMapper;


    @Override
    public List<CompanyVO> findListAll() {
        //获取全部企业
        List<Company> companyList = companyMapper.selectListAll();
        List<CompanyVO> companyVOList = companyList.stream().map(company->{
            CompanyVO companyVO = new CompanyVO();
            BeanUtils.copyProperties(company,companyVO);
            List<Industry> industryList = industryMapper.selectIndustryListByCompany(company.getId());
            companyVO.setIndustryList(industryList);
            return companyVO;
        }).collect(Collectors.toList());
        return companyVOList;
    }

    //启用禁用公司
    public boolean updateCompanyStatus(Integer id, Integer state) {
        int result = companyMapper.updateCompanyStatus(id, state);
        return result > 0;
    }

//    分页查询
@Override
public Page<Company> findAllCompanies(int pageNum, int pageSize, String shortName, Integer isDis) {
    // 使用 PageHelper 分页
    PageHelper.startPage(pageNum, pageSize);
    // 调用 Mapper 查询
    List<Company> companies = companyMapper.selectAllCompanies(shortName, isDis);

    return (Page<Company>) companies;
}

//新增企业
@Transactional
public void addCompany(Company company) {
    // 格式化日期时间
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String formattedDate = sdf.format(new Date());
    company.setCreateDate(formattedDate);

    companyMapper.insertCompany(company);
}

//删除企业
@Transactional
public void deleteCompany(int id) {
    companyMapper.deleteCompanyById(id);
}

}
